package lazy_save_service

import (
	"sen-golang-study/go_game_study/hero_story_go_server/common/log"
	"sync"
	"time"
)

// 延迟保存记录字典,
var lazySaveRecordMap = &sync.Map{}

// 模块初始化时就开始保存
func init() {
	startSave()
}

// SaveOrUpdate 保存或更新
func SaveOrUpdate(saver LazySaver) {
	if nil == saver {
		return
	}

	log.Info(
		"记录延迟保存数据, LazySaver Id = %+v",
		saver.GetId(),
	)

	currRecord, _ := lazySaveRecordMap.Load(saver.GetId())

	if nil != currRecord {
		// 修改最后更新时间
		currRecord.(*lazySaveRecord).lastUpdateTime = time.Now().UnixMilli()
		return
	}

	newRecord := &lazySaveRecord{
		saver:          saver,
		lastUpdateTime: time.Now().UnixMilli(),
	}

	lazySaveRecordMap.Store(saver.GetId(), newRecord)
}

// 开始保存
func startSave() {
	go func() {
		for {
			// 先休息 1 秒
			time.Sleep(time.Second)

			nowTime := time.Now().UnixMilli()
			toDeleteLazySaverIdArray := make([]string, 64)

			lazySaveRecordMap.Range(func(_, val interface{}) bool {
				if nil == val {
					return true
				}

				currRecord := val.(*lazySaveRecord)

				if nowTime-currRecord.lastUpdateTime < 20000 {
					// 如果时间差小于 20 秒
					// 不进行保存
					return true
				}

				log.Info(
					"执行延迟保存, lazySaverId = %+v",
					currRecord.saver.GetId(),
				)

				currRecord.saver.SaveOrUpdate()
				toDeleteLazySaverIdArray = append(toDeleteLazySaverIdArray, currRecord.saver.GetId())
				return true
			})

			for _, lazySaverId := range toDeleteLazySaverIdArray {
				lazySaveRecordMap.Delete(lazySaverId)
			}
		}
	}()
}
